from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from ..db import get_db
from .. import models, schemas
from ..security import get_current_user

router = APIRouter()

@router.post("/", response_model=schemas.ExamOut)
def create_exam(payload: schemas.ExamCreate, db: Session = Depends(get_db), current=Depends(get_current_user)):
    if not payload.title:
        raise HTTPException(status_code=400, detail="title is required")
    exam = models.Exam(title=payload.title, owner_id=current.id)
    db.add(exam)
    db.flush()
    order_counter = 1
    for iid in (payload.issue_ids or []):
        db.add(models.ExamItem(exam_id=exam.id, item_type="issue", ref_id=iid, order=order_counter)); order_counter += 1
    for kid in (payload.knowledge_ids or []):
        db.add(models.ExamItem(exam_id=exam.id, item_type="knowledge", ref_id=kid, order=order_counter)); order_counter += 1
    for rid in (payload.review_ids or []):
        db.add(models.ExamItem(exam_id=exam.id, item_type="review", ref_id=rid, order=order_counter)); order_counter += 1
    db.commit()
    items = db.query(models.ExamItem).filter(models.ExamItem.exam_id == exam.id).order_by(models.ExamItem.order.asc()).all()
    return {"id": exam.id, "title": exam.title, "created_at": exam.created_at, "items": items}

@router.post("", response_model=schemas.ExamOut)
def create_exam_noslash(payload: schemas.ExamCreate, db: Session = Depends(get_db), current=Depends(get_current_user)):
    """Alias without trailing slash to avoid 307 redirect from /api/exams to /api/exams/ on POST."""
    return create_exam(payload, db, current)


@router.get("/", response_model=List[schemas.ExamOut])
def list_exams(db: Session = Depends(get_db), current=Depends(get_current_user)):
    exams = db.query(models.Exam).filter(models.Exam.owner_id == current.id).order_by(models.Exam.created_at.desc()).all()
    result = []
    for e in exams:
        items = db.query(models.ExamItem).filter(models.ExamItem.exam_id == e.id).order_by(models.ExamItem.order.asc()).all()
        result.append({"id": e.id, "title": e.title, "created_at": e.created_at, "items": items})
    return result


@router.get("", response_model=List[schemas.ExamOut])
def list_exams_noslash(db: Session = Depends(get_db), current=Depends(get_current_user)):
    """Alias without trailing slash to avoid 307 redirect between /api/exams and /api/exams/."""
    return list_exams(db, current)

@router.get("/{exam_id}", response_model=schemas.ExamOut)
def get_exam(exam_id: int, db: Session = Depends(get_db), current=Depends(get_current_user)):
    exam = db.query(models.Exam).filter(models.Exam.id == exam_id, models.Exam.owner_id == current.id).first()
    if not exam:
        raise HTTPException(status_code=404, detail="Exam not found")
    items = db.query(models.ExamItem).filter(models.ExamItem.exam_id == exam.id).order_by(models.ExamItem.order.asc()).all()
    return {"id": exam.id, "title": exam.title, "created_at": exam.created_at, "items": items}
